package com.kye.express.business.jd.goods_detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.widget.ImageView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.jakewharton.rxbinding2.view.RxView;
import com.kennyc.bottomsheet.BottomSheet;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.jd.address.JDAddressListActivity;
import com.kye.express.business.jd.goods_detail.model.JDAddressModel;
import com.kye.express.business.jd.goods_detail.viewbinder.JDAddressSelectionViewBinder;
import com.kye.express.business.verification.ExchangeVerificationService;
import com.kye.express.databinding.ActivityJdGoodsDetailBinding;
import com.kye.express.databinding.BottomSheetJdAddressSelectionBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.base.Data4ResultSet;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.integral.IntegralUserBean;
import com.kye.model.bean.jd.address.JDAddressBean;
import com.kye.model.bean.jd.goods_detail.JDCheckGoodsAvailableResultBean;
import com.kye.model.bean.jd.goods_detail.JDGoodsDetailInfoBean;
import com.kye.model.bean.jd.order_details.request.RequestGooodsExchange;
import com.kye.model.bean.jd.shop.JDGoodsItemBean;
import com.kye.model.bean.jd.shop.JDGoodsListResultBean;
import com.kye.model.bean.jd.shop.JDGoodsSkuImageBean;
import com.kye.model.bean.user.User;
import com.kye.nb.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 30/01/2018
 * @updated : 30/01/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class JDGoodsDetailActivity extends BaseToolbarActivity implements JDGoodsDetailContract.JDGoodsDetailView, ExchangeVerificationService.OnVerificationOptionByAutoSendListener, ExchangeVerificationService.OnVerificationOptionByPictureSmsListener {

    private static final int REQUEST_ADDRESS = 1001;
    private static final String TAG_GOODS_DETAIL_ITEM = "TAG_GOODS_DETAIL_ITEM";
    private JDGoodsDetailContract.JDGoodsDetailPresenter presenter;
    private ActivityJdGoodsDetailBinding binding;
    private User userInfo;
    private JDGoodsItemBean jdGoodsItemBean; // 入参，当前商品信息

    IntegralUserBean integralUserBean; // 用户积分信息
    JDGoodsListResultBean goodsListResultBean; // 商品轮播图
    JDGoodsDetailInfoBean jdGoodsDetailInfoBean; // 商品详情
    List<JDAddressBean> jdAddressBeans;
//    JDAddressBean jdAddressBeanSelected; // 地址管理返回选中的新地址

    private MultiTypeAdapter addressAdapter;
    JDAddressModel preSelectedAddress; // 之前选中的,默认选中的
    JDAddressModel selectedAddress; // 当前选中的地址
    List<JDAddressModel> jdAddressModels = new ArrayList<>(); // 用户的京东地址列表
    private Dialog dialog; // loading dialog

    private ExchangeVerificationService exchangeVerificationService;
    private JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean; // 是否有货数据

    public static void startActivity(Context context, JDGoodsItemBean goodsItemBean) {
        Intent intent = new Intent(context, JDGoodsDetailActivity.class);
        intent.putExtra(TAG_GOODS_DETAIL_ITEM, goodsItemBean);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            jdGoodsItemBean = getIntent().getParcelableExtra(TAG_GOODS_DETAIL_ITEM);
        } else {
            jdGoodsItemBean = savedInstanceState.getParcelable(TAG_GOODS_DETAIL_ITEM);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jd_goods_detail);
        presenter = new JDGoodsDetailContract.JDGoodsDetailPresenter();
        initToolbar(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(TAG_GOODS_DETAIL_ITEM, jdGoodsItemBean);
        super.onSaveInstanceState(outState);
    }

    private void initToolbar(Bundle savedInstanceState) {
        ToolbarManager.setToolbar(this, binding.toolbar);
        binding.toolbar.setTitleTextColor(getResources().getColor(R.color.white));
    }

    private void initViews(Bundle savedInstanceState) {

    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorServer.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNet.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmpty.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.refresh(userInfo, jdGoodsItemBean);
            }
        });
        RxView.clicks(binding.toSelectAddress)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * 选择地址
                         */
                        showJDAddressSelectionBottomSheet(jdAddressModels);
                    }
                });
        RxView.clicks(binding.exchangeRightNow)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo :
                         * 立即兑换
                         * 1.是否有收货地址，没有跳转到添加地址界面
                         * 2.判断该地址是否有货
                         */
//                        presenter.toExchange(userInfo, selectedAddress, integralUserBean);
                        if (selectedAddress == null) {
                            // 无选中地址
                            ToastManager.show(JDGoodsDetailActivity.this, "请选择配送地址");
                            JDAddressListActivity.startActivity(JDGoodsDetailActivity.this, REQUEST_ADDRESS, null);
                        } else {
                            Logger.d("====> selected address : " + GsonUtils.toJsonString(selectedAddress, true));
//                            if (!binding.available.isShown()) {
//                                // 无货
//                                ToastManager.show(JDGoodsDetailActivity.this, "当前配送地址无货。");
//                            } else {
//                                // 有货
//                            }
                            presenter.checkBeforeExchange(userInfo, selectedAddress, jdGoodsItemBean, integralUserBean);
                        }
                    }
                });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.bind(this);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        binding.statusLayout.showLoadingView();
        exchangeVerificationService = new ExchangeVerificationService(user.getPhone(), 1);
        exchangeVerificationService.setProvider(getProvider());
    }

    @Override
    public void refreshSuccess(Data4ResultSet<OpenApiResult<IntegralUserBean>, OpenApiResult<JDGoodsListResultBean>, OpenApiResult<JDGoodsDetailInfoBean>, OpenApiResult<List<JDAddressBean>>> data4ResultSet) {
        // todo : 保证地址验证初始化后显示内容界面
//        binding.statusLayout.showContentView();
        /**
         * update view
         */
        integralUserBean = data4ResultSet.data1.getData();
        goodsListResultBean = data4ResultSet.data2.getData();
        jdGoodsDetailInfoBean = data4ResultSet.data3.getData();
        jdAddressBeans = data4ResultSet.data4.getData();

        updateIntegralInfo(integralUserBean);
        updateGoodsBanner(goodsListResultBean);
        updateGoodsDetailInfo(jdGoodsDetailInfoBean);
        // todo :
        updateGoodsAddress(jdAddressBeans);
    }

    /**
     * 更新商品详情信息
     * @param jdGoodsDetailInfoBean
     */
    private void updateGoodsDetailInfo(JDGoodsDetailInfoBean jdGoodsDetailInfoBean) {
        binding.setGoodsDetailData(jdGoodsDetailInfoBean);
        binding.setGoodsItemData(jdGoodsItemBean);
        double exchangeRate = integralUserBean.getExchangeRate();
//        double needScore = jdGoodsItemBean.getNeedScore() * exchangeRate;
        double needScore = jdGoodsItemBean.getNeedScore();
        Double score;
        if (needScore > 10000) {
            score = needScore / 10000;
            binding.goodsIntegral.setText(String.format("%.2f", score.doubleValue()) + "万积分");
        } else {
            score = needScore;
            binding.goodsIntegral.setText(score.intValue() + "积分");
        }
        Logger.d("updateGoodsDetailInfo : \n" + GsonUtils.toJsonString(jdGoodsDetailInfoBean, true));
        String detailContent = jdGoodsDetailInfoBean.getParam() + jdGoodsDetailInfoBean.getIntroduction();
        WebSettings webSettings = binding.webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        binding.webview.loadData(detailContent, "text/html; charset=utf-8", "UTF-8");
    }

    /**
     * 更新配送地址
     * @param jdAddressBeans
     */
    private void updateGoodsAddress(List<JDAddressBean> jdAddressBeans) {
        Logger.d("updateGoodsAddress : \n" + GsonUtils.toJsonString(jdAddressBeans, true));
        /**
         * 1.处理默认地址
         */
        if (jdAddressBeans != null && jdAddressBeans.size() > 0) {
            Observable.fromIterable(jdAddressBeans)
                    .map(new Function<JDAddressBean, JDAddressModel>() {
                        @Override
                        public JDAddressModel apply(JDAddressBean jdAddressBean) throws Exception {
                            JDAddressModel jdAddressModel = new JDAddressModel();
                            jdAddressModel.setSelected(jdAddressBean.isIsDefault());
                            jdAddressModel.setAddressBean(jdAddressBean);
                            return jdAddressModel;
                        }
                    })
                    .toList()
                    .doOnSuccess(new Consumer<List<JDAddressModel>>() {
                        @Override
                        public void accept(List<JDAddressModel> addressModels) throws Exception {
                            jdAddressModels = addressModels;
                        }
                    })
                    .toObservable()
                    .flatMap(new Function<List<JDAddressModel>, ObservableSource<JDAddressModel>>() {
                        @Override
                        public ObservableSource<JDAddressModel> apply(List<JDAddressModel> addressModels) throws Exception {
                            return Observable.fromIterable(addressModels);
                        }
                    })
                    .any(new Predicate<JDAddressModel>() {
                        @Override
                        public boolean test(JDAddressModel jdAddressModel) throws Exception {
                            return jdAddressModel.isSelected();
                        }
                    })
                    .flatMap(new Function<Boolean, SingleSource<List<JDAddressModel>>>() {
                        @Override
                        public SingleSource<List<JDAddressModel>> apply(Boolean hasDefault) throws Exception {
                            if (!hasDefault) {
                                jdAddressModels.get(0).setSelected(true);
                            }
                            return Single.just(jdAddressModels);
                        }
                    })
                    // todo : 获取默认的
                    .toObservable()
                    .flatMap(new Function<List<JDAddressModel>, ObservableSource<JDAddressModel>>() {
                        @Override
                        public ObservableSource<JDAddressModel> apply(List<JDAddressModel> addressModels) throws Exception {
                            return Observable.fromIterable(addressModels);
                        }
                    })
                    .filter(new Predicate<JDAddressModel>() {
                        @Override
                        public boolean test(JDAddressModel jdAddressModel) throws Exception {
                            return jdAddressModel.isSelected();
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<JDAddressModel>() {
                        @Override
                        public void accept(JDAddressModel jdAddressModel) throws Exception {
                            preSelectedAddress = jdAddressModel;
                            selectedAddress = jdAddressModel;
                            presenter.checkGoodsAvailableByAddressFirst(userInfo, selectedAddress, jdGoodsItemBean.getSku());
                        }
                    });
        } else {
            /**
             * todo : 无默认地址
             */
            preSelectedAddress = null;
            selectedAddress = null;
            binding.statusLayout.showContentView();
            binding.address.setText("暂无收货地址");
            binding.available.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void updateGoodsAddressNoAddress() {
        /**
         * todo : 无默认地址
         */
        preSelectedAddress = null;
        selectedAddress = null;
        binding.address.setText("暂无收货地址");
        binding.available.setVisibility(View.INVISIBLE);
    }

    @Override
    public void checkGoodsAvailableSuccessFirst(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
        binding.statusLayout.showContentView();
        if (jdCheckGoodsAvailableResultBean.getStatus().equals("1")) {
            // 有货
            binding.address.setText(selectedAddress.getAddressBean().getAddress());
            binding.available.setVisibility(View.VISIBLE);
        } else {
            // 无货
            binding.address.setText("本礼品暂时无货，请兑换其他礼品");
            binding.available.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void checkGoodsUnAvailableSuccessFirst(OpenApiResult<JDCheckGoodsAvailableResultBean> result) {
        binding.statusLayout.showContentView();
        // 无货
        binding.address.setText("本礼品暂时无货，请兑换其他礼品");
        binding.available.setVisibility(View.INVISIBLE);
    }

    @Override
    public void checkGoodsAvailableServerFailedFirst(String msg) {
        ToastManager.show(this, msg);
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void checkGoodsAvailableNetFailedFirst(String message) {
        ToastManager.show(this, message);
        binding.statusLayout.showErrorNetworkView();
    }

    /**
     * 更新轮播图
     * @param goodsListResultBean
     */
    private void updateGoodsBanner(JDGoodsListResultBean goodsListResultBean) {
        Logger.d("updateGoodsBanner : \n" + GsonUtils.toJsonString(goodsListResultBean.getDatas(), true));
        Observable.just(goodsListResultBean.getDatas().get(0))
                .map(new Function<JDGoodsItemBean, HashMap<String, ArrayList<JDGoodsSkuImageBean>>>() {
                    @Override
                    public HashMap<String, ArrayList<JDGoodsSkuImageBean>> apply(JDGoodsItemBean goodsItemBean) throws Exception {
                        return goodsItemBean.getSkuImage();
                    }
                })
                .flatMap(new Function<HashMap<String, ArrayList<JDGoodsSkuImageBean>>, ObservableSource<JDGoodsSkuImageBean>>() {
                    @Override
                    public ObservableSource<JDGoodsSkuImageBean> apply(HashMap<String, ArrayList<JDGoodsSkuImageBean>> stringArrayListHashMap) throws Exception {
                        return Observable.fromIterable(stringArrayListHashMap.get(jdGoodsItemBean.getSku()));
                    }
                })
                .map(new Function<JDGoodsSkuImageBean, String>() {
                    @Override
                    public String apply(JDGoodsSkuImageBean jdGoodsSkuImageBean) throws Exception {
                        return "http://img13.360buyimg.com/n0/" + jdGoodsSkuImageBean.getPath();
                    }
                })
                .toList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> adImages) throws Exception {
                        binding.banner.setDelayTime(4000);
                        binding.banner.setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                                Glide.with(context)
                                        .load(path)
                                        .apply(new RequestOptions().error(R.drawable.error).placeholder(R.drawable.background_about_empty).centerInside())
                                        .into(imageView);
                            }
                        });
                        binding.banner.setImages(adImages);
                        binding.banner.start();
                    }
                });
    }

    /**
     * todo : 更新用户积分
     * @param integralUserBean
     */
    private void updateIntegralInfo(IntegralUserBean integralUserBean) {
        // 是否跨越用户 1:是
        // 可用积分
        int kyeUser = integralUserBean.getKyeUser();
        switch (kyeUser) {
            case 0:
                Double systemIntegralOne = Double.valueOf(integralUserBean.getSystemIntegralOne());
                if (systemIntegralOne > 10000) {
                    binding.integralAvailable.setText((String.format("%.2f", systemIntegralOne / 10000)) + "万");
                } else {
                    binding.integralAvailable.setText(systemIntegralOne.intValue() + "");
                }
                break;
            case 1:
                Double jdIntegral = Double.valueOf(integralUserBean.getJdIntegral());
                if (jdIntegral > 10000) {
                    binding.integralAvailable.setText((String.format("%.2f", jdIntegral / 10000)) + "万");
                } else {
                    binding.integralAvailable.setText(jdIntegral.intValue() + "");
                }
                break;
        }
        // 当天可用积分
        Double trueAvailableIntegral = Double.valueOf(integralUserBean.getTrueAvailableIntegral());
        if (trueAvailableIntegral > 10000) {
            binding.integralAvailableToday.setText( (String.format("%.2f", trueAvailableIntegral / 10000)) + "万");
        } else {
            binding.integralAvailableToday.setText( trueAvailableIntegral.toString());
        }
    }

    @Override
    public void refreshServerFailed(String message) {
        binding.statusLayout.showErrorServerView();
        ToastManager.show(this, message);
    }

    @Override
    public void refreshNetFailed(String message) {
        binding.statusLayout.showErrorNetworkView();
        ToastManager.show(this, message);
    }

    @Override
    public void showJDAddressSelectionBottomSheet(List<JDAddressModel> jdAddressModels) {
        Logger.d("address List : \n" + GsonUtils.toJsonString(jdAddressModels, true));
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        BottomSheetJdAddressSelectionBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.bottom_sheet_jd_address_selection, null, false);
        final BottomSheet bottomSheet = new BottomSheet.Builder(this)
                .setView(binding.getRoot()).create();
        addressAdapter = new MultiTypeAdapter();
        addressAdapter.register(JDAddressModel.class, new JDAddressSelectionViewBinder(new JDAddressSelectionViewBinder.OnAddressItemListener() {
            @Override
            public void onAddressItemClicked(JDAddressModel preSelected, JDAddressModel selected, List<JDAddressModel> addressModels) {
                JDGoodsDetailActivity.this.jdAddressModels = addressModels;
                preSelectedAddress = preSelected;
                selectedAddress = selected;
                Logger.d("preSelectedAddress : \n" + GsonUtils.toJsonString(preSelectedAddress, true));
                Logger.d("selectedAddress    : \n" + GsonUtils.toJsonString(selectedAddress, true));
                Logger.d("jdAddressModels    : \n" + GsonUtils.toJsonString(jdAddressModels, true));
                /**
                 * todo : check goods available
                 */
                presenter.checkGoodsAvailableByAddress(userInfo, selected, jdGoodsItemBean.getSku());
                addressAdapter.notifyDataSetChanged();
                bottomSheet.dismiss();
            }
        }));
        RxView.clicks(binding.selectOtherAddress)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 添加新的地址
                         * 返回后重新刷新地址
                         */
                        bottomSheet.dismiss();
                        if (selectedAddress == null) {
                            JDAddressListActivity.startActivity(JDGoodsDetailActivity.this, REQUEST_ADDRESS, null);
                        } else {
                            JDAddressListActivity.startActivity(JDGoodsDetailActivity.this, REQUEST_ADDRESS, selectedAddress.getAddressBean());
                        }
                    }
                });
        RxView.clicks(binding.close)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        bottomSheet.dismiss();
                    }
                });
        addressAdapter.setItems(jdAddressModels);
        binding.jdAddresses.setLayoutManager(new LinearLayoutManager(this));
        binding.jdAddresses.setAdapter(addressAdapter);
        bottomSheet.show();
    }

    @Override
    public void checkGoodsAvailableSuccess(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
        if (jdCheckGoodsAvailableResultBean.getStatus().equals("1")) {
            // 有货
            binding.address.setText(selectedAddress.getAddressBean().getAddress());
            binding.available.setVisibility(View.VISIBLE);
        } else {
            // 无货
            binding.address.setText("本礼品暂时无货，请兑换其他礼品");
            binding.available.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void checkGoodsUnAvailableSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result) {
        // 无货
        binding.address.setText("本礼品暂时无货，请兑换其他礼品");
        binding.available.setVisibility(View.INVISIBLE);
    }

    @Override
    public void checkGoodsAvailableServerFailed(String msg) {
        preSelectedAddress.setSelected(true);
        selectedAddress.setSelected(false);
        ToastManager.show(this, msg);
    }

    @Override
    public void checkGoodsAvailableNetFailed(String message) {
        preSelectedAddress.setSelected(true);
        selectedAddress.setSelected(false);
        ToastManager.show(this, message);
    }

    @Override
    public void checkGoodsAvailableFromAddressManageSuccess(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
        this.jdCheckGoodsAvailableResultBean = jdCheckGoodsAvailableResultBean;
        if (jdCheckGoodsAvailableResultBean.getStatus().equals("1")) {
            // 有货
            binding.address.setText(selectedAddress.getAddressBean().getAddress());
            binding.available.setVisibility(View.VISIBLE);
        } else {
            // 无货
            binding.address.setText("本礼品暂时无货，请兑换其他礼品");
            binding.available.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void checkGoodsUnAvailableFromAddressManageSuccess(OpenApiResult<JDCheckGoodsAvailableResultBean> result) {
        // 无货
        binding.address.setText("本礼品暂时无货，请兑换其他礼品");
        binding.available.setVisibility(View.INVISIBLE);
    }

    @Override
    public void checkGoodsAvailableFromAddressManageServerFailed(String msg) {
        selectedAddress.setSelected(false);
        preSelectedAddress.setSelected(false);
        ToastManager.show(this, msg);
    }

    @Override
    public void checkGoodsAvailableNetFromAddressManageFailed(String message) {
        selectedAddress.setSelected(false);
        preSelectedAddress.setSelected(false);
        ToastManager.show(this, message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * todo : 处理地址管理的操作结果
         */
        if (requestCode == REQUEST_ADDRESS) {
            JDAddressBean addressBean = data.getParcelableExtra("data");
            List<JDAddressBean> addressBeanList = data.getParcelableArrayListExtra("datas");
            Logger.d("addressBean : " + GsonUtils.toJsonString(addressBean, true));
            Logger.d("addressBeanList : " + GsonUtils.toJsonString(addressBeanList, true));

            switch (resultCode) {
                case JDAddressListActivity.RESULT_CODE_ADDRESS_SELECT:
                    // 选中了地址返回，设置为默认的地址,并且刷新判断是否有货
                    presenter.updateSelectedAddress(addressBean, addressBeanList, jdGoodsItemBean.getSku(), userInfo);
                    break;
                case JDAddressListActivity.RESULT_CODE_ADDRESS_UPDATE:
                    // 需要重新刷新地址列表,如果有地址返回初始化返回的地址为默认,并且判断是否有货
                    // todo : 地址管理返回可能删除了详情选中的地址
                    presenter.updateSelectedAddress(addressBean, addressBeanList, jdGoodsItemBean.getSku(), userInfo);
                    break;
                case Activity.RESULT_OK:
                    /**
                     * todo : 京东兑换成功
                     */
                    Logger.d("京东兑换成功");
                    finish();
                    break;
                case Activity.RESULT_CANCELED:
                    Logger.d("cancel");
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 兑换消费，人气，短信状态检查
     */
    @Override
    public void checkStateBeforeExchange() {

        exchangeVerificationService.check(new ExchangeVerificationService.OnVerificationCheckListener() {

            @Override
            public void onLoading() {
                JDGoodsDetailActivity.this.onLoading();
            }

            @Override
            public void onLoaded() {
                JDGoodsDetailActivity.this.onLoaded();
            }

            @Override
            public void onCannotExchangeError(String msg) {
                // todo : 跳转到人气支持

            }

            @Override
            public void onNeedSendSmsError(String msg, String smsChannel, String type, String phone) {
                exchangeVerificationService.showVerificationByAutoSendMessage(JDGoodsDetailActivity.this, 2, phone, smsChannel, JDGoodsDetailActivity.this);
            }

            @Override
            public void onAccountError(String msg, String smsChannel, String type, String phone) {
                ToastManager.show(JDGoodsDetailActivity.this, msg);
            }

            @Override
            public void onOpenApiError(OpenApiResult openApiResult) {
                ToastManager.show(JDGoodsDetailActivity.this, openApiResult.getMsg());
            }

            @Override
            public void onOtherError(Throwable e) {
                ToastManager.show(JDGoodsDetailActivity.this, e.getMessage());
            }

            @Override
            public void onVerifyByAutoSendMessage(String smsChannel, String type, String phone) {
                exchangeVerificationService.showVerificationByAutoSendMessage(JDGoodsDetailActivity.this, 2, phone, smsChannel, JDGoodsDetailActivity.this);
            }

            @Override
            public void onVerifyByPictureSms(String smsChannel, String type, String phone) {
                exchangeVerificationService.showVerificationByPictureSmsDialog(JDGoodsDetailActivity.this, 2, JDGoodsDetailActivity.this);
            }
        });
    }

    @Override
    public void getPictureCodeSuccess(byte[] picture) {

    }

    @Override
    public void onSendSmsCodeSuccess() {

    }

    /**
     * 兑换
     * @param smsCodeInput
     */
    @Override
    public void toExchange1(String smsCodeInput, MaterialDialog dialog) {

    }

    /**
     * 兑换
     * @param smsCodeInput
     */
    @Override
    public void toExchange2(String smsCodeInput, MaterialDialog dialog) {

    }

    @Override
    public void toExchangePage(JDCheckGoodsAvailableResultBean jdCheckGoodsAvailableResultBean) {
        RequestGooodsExchange requestGooodsExchange = new RequestGooodsExchange();
        requestGooodsExchange.setKySign("123456");
        requestGooodsExchange.setSkuId(jdGoodsItemBean.getSku());
        requestGooodsExchange.setName(selectedAddress.getAddressBean().getReviceName());
        requestGooodsExchange.setProvince(selectedAddress.getAddressBean().getProvince());
        requestGooodsExchange.setProvinceName(selectedAddress.getAddressBean().getProvinceStr());
        requestGooodsExchange.setCity(selectedAddress.getAddressBean().getCity());
        requestGooodsExchange.setCityName(selectedAddress.getAddressBean().getCityStr());
        requestGooodsExchange.setCounty(selectedAddress.getAddressBean().getCountry());
        requestGooodsExchange.setCountyName(selectedAddress.getAddressBean().getCountryStr());
        JDAddressBean addressBean = selectedAddress.getAddressBean();
        if (addressBean == null || TextUtils.isEmpty(addressBean.getTown()) || "0".equals(addressBean.getTown())) {
            requestGooodsExchange.setTown("0");
            requestGooodsExchange.setTownName("");
        } else {
            requestGooodsExchange.setTown(selectedAddress.getAddressBean().getTown());
            requestGooodsExchange.setTownName(selectedAddress.getAddressBean().getTownStr());
        }
        requestGooodsExchange.setAddress(selectedAddress.getAddressBean().getAddress());
        requestGooodsExchange.setMobile(selectedAddress.getAddressBean().getReviceTel());
        if (TextUtils.isEmpty(requestGooodsExchange.getMobile())) {
            requestGooodsExchange.setMobile(userInfo.getPhone());
        }
        requestGooodsExchange.setCodeMoney(String.valueOf(jdGoodsItemBean.getPrice()));
        requestGooodsExchange.setPhone(userInfo.getPhone());
        requestGooodsExchange.setPhoneNumber(userInfo.getPhone());
        requestGooodsExchange.setConsCredit(String.valueOf(jdGoodsItemBean.getNeedScore()));
        requestGooodsExchange.setAllowContFlag("1");
//        requestGooodsExchange.setConfirmCode();
        requestGooodsExchange.setOrderAmount(String.valueOf(jdGoodsItemBean.getPrice()));
        Logger.d("requestGooodsExchange : " + GsonUtils.toJsonString(requestGooodsExchange, true));
        JDGoodsExchangeActivity.startActivity(this,  REQUEST_ADDRESS, selectedAddress.getAddressBean(), jdCheckGoodsAvailableResultBean, requestGooodsExchange);
//        exchangeVerificationService.showVerificationByAutoSendMessage(this, 2, "123123123", "123123123", new ExchangeVerificationService.OnVerificationOptionByAutoSendListener() {
//            @Override
//            public void onLoading() {
//                JDGoodsDetailActivity.this.onLoading();
//            }
//
//            @Override
//            public void onLoaded() {
//                JDGoodsDetailActivity.this.onLoaded();
//            }
//
//            @Override
//            public void toExchange2(String smsCodeInput, MaterialDialog dialog) {
//                Logger.d("toExchange2 : " + smsCodeInput);
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        if (binding.webview != null) {
            binding.webview.loadDataWithBaseURL(null, "", "text/html; charset=utf-8", "UTF-8", null);
            binding.webview.clearHistory();
            ((ViewGroup) binding.webview.getParent()).removeView(binding.webview);
            binding.webview.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }

    @Override
    public List<JDAddressModel> getJdAddressModels() {
        return jdAddressModels;
    }

    @Override
    public void setJdAddressModels(List<JDAddressModel> jdAddressModels) {
        this.jdAddressModels = jdAddressModels;
    }

    @Override
    public JDAddressModel getPreSelectedAddress() {
        return preSelectedAddress;
    }

    @Override
    public void setPreSelectedAddress(JDAddressModel preSelectedAddress) {
        this.preSelectedAddress = preSelectedAddress;
    }

    @Override
    public JDAddressModel getSelectedAddress() {
        return selectedAddress;
    }

    @Override
    public void setSelectedAddress(JDAddressModel selectedAddress) {
        this.selectedAddress = selectedAddress;
    }

    @Override
    public Context getContext() {
        return this;
    }
}
